import os
import re
from openai import OpenAI
from src.skill_recode import SkillRecoder
# 全局变量：翻译模式标志
 # 默认为False，设置为True时进入翻译模式

class Skill:
    name: str
    contents = []
    translations = []
    def __init__(self, name, contents, trans):
        self.name = name
        self.contents = contents
        self.translations = trans

class GPT:
    basic_prompt: str # 用来指示技能基本架构如何进行改变的prompt
    misc_prompt: str
    askto_prompt: str # 用来杀askFor系列的prompt
    model = "qwen3-235b-a22b" # 用ollama创建的context window增大版的model

    def __init__(self):
        dir_path = os.path.dirname(os.path.abspath(__file__))
        base_path = os.path.join(dir_path, "prompts")
        with open(os.path.join(base_path, "01-basic.md"), encoding='utf-8') as f:
            self.basic_prompt = f.read()
        with open(os.path.join(base_path, "02-misc.md"), encoding='utf-8') as f:
            self.misc_prompt = f.read()
        with open(os.path.join(base_path, "03-askto.md"), encoding='utf-8') as f:
            self.askto_prompt = f.read()
        
        # 根据自己需求修改key
        # 不过如果用的是公开厂商的API key，那么绝对不要公布出来！
        # 这里是我本地部署的ai所以我就对key随便处理了
        api_end_point ="https://dashscope.aliyuncs.com/compatible-mode/v1"
        api_key = "sk-0a29ee3b205242a9981c9b363d5ce7ce"
        self.client = OpenAI(api_key=api_key, base_url=api_end_point)

    def chat(self, sys_prompt, skill) -> str:
        return self.client.chat.completions.create(
            model=self.model,
            messages=[
                {"role": "system", "content": sys_prompt},
                {"role": "user", "content": skill},
            ],
            stream=False
        ).choices[0].message.content

# 先就解决一下提取技能和提取武将的问题
class FkPackage:
    skills: dict[str, Skill] = {}
    generals = []
    translations = {}
    extension_name="MahjongSoul"
    istrans = False
    def __init__(self, filepath: str,istrans:bool):
        self.gpt = GPT()
        self.istrans = istrans
        self.filepath = filepath
        print(f"[*] 开始处理文件: {filepath}")
        with open(filepath, 'r', encoding='utf-8') as f:
            self.file_content = f.read()
        self.file_content = self.clean_skill_content(self.file_content)
     
        self._extract_translations()
        self._extract_skills()
        self._extract_generals()
      
            

    '''
  
    '''
    def renameextension(self, newname: str):
        # 如果文件名是扩展包名，则更新extension_name
        if not self.extract_package_name(self.filepath):
            self.extension_name = newname


    def _extract_translations(self):
        self.translations = {}
        # 查找Fk:loadTranslationTable的位置
        start_pattern = re.compile(r'Fk:loadTranslationTable\s*{', re.DOTALL)
        for match in start_pattern.finditer(self.file_content):
            start_pos = match.end()

            # 提取直到匹配的闭合花括号的内容
            brace_count = 1
            current_pos = start_pos
            content = []
            while current_pos < len(self.file_content) and brace_count > 0:
                char = self.file_content[current_pos]
                if char == '{':
                    brace_count += 1
                elif char == '}':
                    next_pos = current_pos + 1
                    if next_pos >= len(self.file_content) or self.file_content[next_pos] in '\r\n':
                        brace_count = 0  # 只有在行尾才停止
                if brace_count > 0:
                    content.append(char)
                current_pos += 1
            table_content = ''.join(content)

            # 去除注释
            # 先处理多行注释
            cleaned_content = re.sub(r'--\[\[(.*?)\]\]', '', table_content, flags=re.DOTALL)
            # 再处理单行注释，但保留注释前的代码
            cleaned_content = re.sub(r'(^|[^-])--.*', r'\1', cleaned_content, flags=re.MULTILINE)
          

            # 分割键值对
            entries = re.split(r',\s*(?=\n|$)', cleaned_content)
   
            for entry in entries:
                entry = entry.strip()
                if not entry:
                    continue

                # 解析键
                key_match = re.match(r'\s*\[\s*(["\'])(.*?)\1\s*\]\s*=\s*(.*)', entry, re.DOTALL)
                
                if not key_match:
                    continue
                quote_type, key_content, value_expr = key_match.groups()
                
                # 打印捕获组3（值表达式）
                
                # 处理键的转义
                key = self._unescape_lua_string(key_content)

                # 解析值中的字符串
                value = self._parse_lua_value(value_expr)

                if key and value is not None:
                    self.translations[key] = value
        
        # 查找T.skilltranslate格式的翻译
        skill_translate_pattern = re.compile(r'T\.skilltranslate\s*\(\s*["\']([^"\']+)["\']\s*,\s*{\s*["\'](.*?)["\']\s*,\s*(\[\[.*?\]\]|\s*["\'](.*?)["\']\s*)', re.DOTALL)
        for match in skill_translate_pattern.finditer(self.file_content):
            skill_key, skill_name, bracket_value, quoted_value = match.groups()
            
            # 添加技能名称的翻译
            self.translations[skill_key] = skill_name
            
            # 添加技能描述的翻译
            if bracket_value and bracket_value.startswith('[['):
                # 提取[[...]]内的内容
                desc_match = re.match(r'\[\[(.*?)\]\]', bracket_value, re.DOTALL)
                if desc_match:
                    self.translations[":" + skill_key] = desc_match.group(1)
            elif quoted_value:
                self.translations[":" + skill_key] = self._unescape_lua_string(quoted_value)
            
     
            
        # 新增：查找T.translate格式的翻译
        translate_pattern = re.compile(r'T\.translate\s*\(\s*["\'](.*?)["\']\s*,\s*["\']([^"\']+)["\']\s*\)', re.DOTALL)
        for match in translate_pattern.finditer(self.file_content):
            key, value = match.groups()
            self.translations[key] = value
 
            
        # 新增：查找T.creategenandtanslatene格式的翻译
        gen_translate_pattern = re.compile(r'local\s+(\w+)\s*=\s*T\.creategenandtanslatene\s*\(\s*{.*?["\']([^"\']+)["\']\s*,\s*["\']([^"\']+)["\']\s*,.*?}\s*,\s*{\s*["\'](.*?)["\']\s*,\s*["\'](.*?)["\']\s*(?:,\s*["\'](.*?)["\']\s*)?}\s*\)', re.DOTALL)
        for match in gen_translate_pattern.finditer(self.file_content):
            groups = match.groups()
            var_name, general_name, kingdom = groups[0], groups[1], groups[2]
            gen_name, gen_title = groups[3], groups[4]
            designer = groups[5] if len(groups) > 5 and groups[5] else "未知"
            
     
            # 存储武将名称 - 使用完整的武将名作为键
            self.translations[general_name] = gen_name
            # 存储武将称号
            self.translations["#" + general_name] = gen_title
            # 存储设计者信息
            if designer != "未知":
                self.translations["designer:" + general_name] = designer
            
     
        # 新增：查找T.skilltrstable格式的翻译表
        skilltr_start_pattern = re.compile(r'T\.skilltrstable\s*{', re.DOTALL)
        for match in skilltr_start_pattern.finditer(self.file_content):
            start_pos = match.end()
            
            # 提取整个表格内容
            brace_count = 1
            current_pos = start_pos
            content = []
            while current_pos < len(self.file_content) and brace_count > 0:
                char = self.file_content[current_pos]
                if char == '{':
                    brace_count += 1
                elif char == '}':
                    brace_count -= 1
                if brace_count > 0:
                    content.append(char)
                current_pos += 1
            table_content = ''.join(content)
            
            # 使用正则表达式匹配每个技能条目
            # 格式: {"skill_key",{"技能名",[[技能描述]]}}
            skill_entries = re.finditer(r'\{\s*["\'](.*?)["\']\s*,\s*\{\s*["\'](.*?)["\']\s*,\s*(\[\[.*?\]\]|["\'](.*?)["\']\s*)\}\s*\}', table_content, re.DOTALL)
            
            for entry in skill_entries:
                skill_key, skill_name, bracket_desc, quoted_desc = entry.groups()
                
                # 存储技能名称
                self.translations[skill_key] = skill_name
       
                
                # 存储技能描述
                if bracket_desc and bracket_desc.startswith('[['):
                    # 提取[[...]]内的内容
                    desc_match = re.match(r'\[\[(.*?)\]\]', bracket_desc, re.DOTALL)
                    if desc_match:
                        self.translations[":" + skill_key] = desc_match.group(1)
                       
                elif quoted_desc:
                    self.translations[":" + skill_key] = self._unescape_lua_string(quoted_desc)
                   
        # 新增：查找T.tablestranslate格式的批量翻译
        table_translate_pattern = re.compile(r'T\.tablestranslate\s*\(\s*{(.*?)}\s*,\s*{(.*?)}\s*\)', re.DOTALL)
        for match in table_translate_pattern.finditer(self.file_content):
            keys_str, values_str = match.groups()
            
            # 提取键和值
            keys = re.findall(r'["\'](.*?)["\']', keys_str)
            values = re.findall(r'["\'](.*?)["\']', values_str)
            
            # 确保键和值的数量一致
            min_len = min(len(keys), len(values))
            
            for i in range(min_len):
                key = self._unescape_lua_string(keys[i])
                value = self._unescape_lua_string(values[i])
                self.translations[key] = value
          

    def _unescape_lua_string(self, s):
        # 处理Lua字符串中的转义字符
        replacements = {
            '\\\\': '\\',
            '\\"': '"',
            "\\'": "'",
            '\\n': '\n',
            '\\t': '\t',
            '\\r': '\r',
            '\\b': '\b',
            '\\f': '\f',
            '\\a': '\a',
            '\\v': '\v'
        }
        for escaped, unescaped in replacements.items():
            s = s.replace(escaped, unescaped)
        return s

    def _parse_lua_value(self, expr):
        # 解析Lua字符串拼接表达式
        str_pattern = re.compile(r'''["']((?:[^\\"']|\\.)*)["']''', re.DOTALL)
        # 新增：匹配[[...]]格式的多行字符串
        bracket_pattern = re.compile(r'''\[\[(.*?)\]\]''', re.DOTALL)
        
        parts = []
        # 先检查是否有[[...]]格式
        bracket_match = bracket_pattern.search(expr)
        if bracket_match:
            # 如果有[[...]]格式，直接返回其内容
            return bracket_match.group(1)
            
        # 常规引号字符串处理
        for match in str_pattern.finditer(expr):
            str_content = match.group(1)
            parts.append(self._unescape_lua_string(str_content))
        return ''.join(parts) if parts else None

    '''
    把东西作为字典放入自己的skills里面
    name: 技能名，content: 源代码内容
    translations: 翻译表

    技能的格式为：
    local xxx = fk.CreateXXXSkill {
      <中间全部>
    }
    xxx:addRelatedSkill(yyy)

    如果某个技能是为了被addRelatedSkill而创建的，那他就不是
    
    翻译表是{ key: "xxx", value: "yyy" }格式的数组。检索方法是首先
    找出代码内容中全部字符串，然后再从整个文件中找形如["xxx"] = "yyy"的行
    （单引号亦可，后者可能有折行），将这样的加入到translation中。

    最后加入数组
    '''
    def _extract_skills(self):
        self.skills = {}
        skill_pattern = re.compile(r'local\s+(\w+)\s*=\s*fk\.Create\w+Skill\s*\{', re.IGNORECASE)
        for match in skill_pattern.finditer(self.file_content):
            skill_name = match.group(1) 
           
       
            start_pos = match.start()
            level = 1
            end_pos = match.end()
            while end_pos < len(self.file_content) and level > 0:
                char = self.file_content[end_pos]
                if char == '{':
                    level += 1
                elif char == '}':
                    level -= 1
                end_pos += 1
            content = self.file_content[start_pos:end_pos]  # 提取完整技能内容
            #print(f"content:{content}")
            skill_str_name = re.compile(r'name\s*=\s*["\'](.*?)["\']').findall(content)[0]
    
            self.skills[skill_name] = Skill(skill_str_name, [content], [])
            
        related_pattern = re.compile(r'(\w+):addRelatedSkill\(\s*(\w+)\s*\)')
        for match in related_pattern.finditer(self.file_content):
            main_skill = match.group(1)
            sub_skill = match.group(2)
            if not main_skill in self.skills:
                continue
            if not sub_skill in self.skills:
                continue
            main_skill_obj = self.skills[main_skill]
            sub_skill_obj = self.skills[sub_skill]
            main_skill_obj.contents.append(sub_skill_obj.contents[0])
            
            # 在非翻译模式下才删除子技能
            if not self.istrans:
                del self.skills[sub_skill]


            # 不再收集每个技能的翻译，统一由create_translation_file处理

    def _extract_generals(self):
        """提取武将信息"""
        self.generals = []
        
        # 情况1：查找创建武将的格式，如General:new(extension, "ty_ex__caozhi", "wei", 3)
        general_pattern = re.compile(r'local\s+(\w+)\s*=\s*General:new\(\s*\w+\s*,\s*["\']([^"\']+)["\']\s*,\s*["\']([^"\']+)["\']\s*,\s*(\d+)(?:\s*,\s*(\d+))?(?:\s*,\s*(General\.\w+))?\s*\)', re.DOTALL)
        
        # 情况2：查找 local n_jisi = General(extension, "n_jisi", "huan", 5) 格式
        general_pattern2 = re.compile(r'local\s+(\w+)\s*=\s*General\(\s*\w+\s*,\s*["\']([^"\']+)["\']\s*,\s*["\']([^"\']+)["\']\s*,\s*(\d+)(?:\s*,\s*(\d+))?(?:\s*,\s*(General\.\w+))?\s*\)', re.DOTALL)
        
        # 情况3：查找T.creategenandtanslatene方法创建的武将
        general_pattern3 = re.compile(r'local\s+(\w+)\s*=\s*T\.creategenandtanslatene\s*\(\s*{.*?["\']([^"\']+)["\']\s*,\s*["\']([^"\']+)["\']\s*,\s*.*?(\d+)(?:\s*,\s*(\d+))?.*?}\s*,', re.DOTALL)
        
        patterns = [
            (general_pattern, 'General:new'),
            (general_pattern2, 'General'),
            (general_pattern3, 'T.creategenandtanslatene')
        ]
        
        for pattern, pattern_name in patterns:
            for match in pattern.finditer(self.file_content):
                localname=match.group(1)
      
                general_name = match.group(2)
                kingdom = match.group(3)
                hp = int(match.group(4))
                maxhp = int(match.group(5)) if match.group(5) else hp
                gender = match.group(6) if pattern_name != 'T.creategenandtanslatene' and match.group(6) else "General.Male"
                
               
                
                skills_patterns = [
                    re.compile(rf'{localname}:addSkill\s*\(\s*(.*?)\s*\)' , re.DOTALL),
                ]
                
                skills = []
                for sp in skills_patterns:
                    # 使用finditer替代search，获取所有匹配
                    for skills_match in sp.finditer(self.file_content):
                        skills_str = skills_match.group(1)
                       
                        # 检查是否为带引号的技能名
                        quoted_skills = re.findall(r'["\'](.*?)["\']', skills_str)
                        if quoted_skills:
                            # 处理带引号的技能名（如"jianxiong"）
                            new_skills = [s.strip().strip('"\'') for s in re.findall(r'["\'](.*?)["\']', skills_str)]
                            for skill_name in new_skills:
                                if skill_name in self.skills:
                                    # 直接使用字符串作为键
                                    skills.append(self.skills[skill_name].name)
                                else:
                                    # 直接添加技能名
                                    skills.append(skill_name)
                        else:
                            # 处理不带引号的技能名（如jianxiong变量）
                            skill_var = skills_str.strip()
                            if skill_var in self.skills:
                                skills.append(self.skills[skill_var].name)
                            # 如果找不到对应变量，可能是其他形式的技能引用，跳过
                
                # 查找相关技能

                related_skills = []
        
                related_patterns = [
                    re.compile(r'%s.*?:addRelatedSkill\s*\(\s*(.*?)\s*\)' % re.escape(localname)),
                ]
                
                for rp in related_patterns:
                    for related_match in rp.finditer(self.file_content):
                        related_str = related_match.group(1)
                        print(f"[*] 找到武将: {general_name} ({pattern_name}方式) 的关联技能: {related_str}")

                        # 同样检查是否为带引号的技能名
                        quoted_related = re.findall(r'["\'](.*?)["\']', related_str)
                        if quoted_related:
                            # 处理带引号的技能名
                            new_related = [s.strip().strip('"\'') for s in re.findall(r'["\'](.*?)["\']', related_str)]
                            for related_name in new_related:
                                if related_name in self.skills:
                                    related_skills.append(self.skills[related_name].name)
                                else:
                                    related_skills.append(related_name)
                        else:
                            # 处理不带引号的技能名（变量）
                            related_var = related_str.strip()
                            if related_var in self.skills:
                                related_skills.append(self.skills[related_var].name)
                     
                            
                            
                            # 跳过找不到的变量


                # 创建武将对象并添加到列表
                
                general_info = {
                    'localname': localname,
                    'name': general_name,
                    'kingdom': kingdom,
                    'hp': hp,
                    'maxhp': maxhp, 
                    'gender': gender,
                    'skills': skills,
                    'related_skills': related_skills,
                }

                #查找武将的hidden，shield,total_hidden属性
                patternmap={
                    "hidden": re.compile(rf'{localname}\.hidden\s*=\s*(\w+)\s*', re.DOTALL),
                    "shield" : re.compile(rf'{localname}\.shield\s*=\s*(\d+)\s*', re.DOTALL),
                    "total_hidden" :  re.compile(rf'{localname}\.total_hidden\s*=\s*(\w+)\s*', re.DOTALL),
                }

                for key,pattern in patternmap.items():
                    match = pattern.search(self.file_content)
                   
                    if match:
                        general_info[key] = match.group(1)










           
                
                # 检查是否已添加过同名武将
                if not any(g['name'] == general_name for g in self.generals):
                    self.generals.append(general_info)
                
            
        print(f"[*] 已提取 {len(self.generals)} 个武将信息")

    def _unescape_unicode(self, text):
        """处理Unicode转义序列，将其转换为实际字符
        
        Args:
            text (str): 包含Unicode转义序列的文本
            
        Returns:
            str: 转换后的文本
        """
        return text.encode('utf-8').decode('unicode_escape')

    def create_translation_file(self):
        """创建包含所有技能翻译的trans.lua文件"""
        # 获取基础路径信息
        dir_path = os.path.dirname(os.path.abspath(self.filepath))
        base_name = os.path.splitext(os.path.basename(self.filepath))[0]
        
        # 创建目标文件夹
        pkg_dir = os.path.join(dir_path, "pkg", base_name)
        os.makedirs(pkg_dir, exist_ok=True)
        
        # 创建trans.lua文件
        trans_file_path = os.path.join(pkg_dir, "trans.lua")
        
        # 构建翻译文件内容
        content = "-- 自动生成的翻译文件\n\n"
        content += "Fk:loadTranslationTable{\n"
        
        # 添加所有翻译
        for key, value in self.translations.items():
            # 处理可能的Unicode转义序列
            #key = self._unescape_unicode(key)
            #value = self._unescape_unicode(value)
            content += f"  [{repr(key)}] = {repr(value)},\n"
        
        content += "}\n"
        
        # 写入文件
        try:
            with open(trans_file_path, 'w', encoding='utf-8') as f:
                f.write(content)
            print(f"[*] 已创建翻译文件: {trans_file_path}")
        except Exception as e:
            print(f"创建翻译文件失败: {trans_file_path} | 错误: {str(e)}")


    #todo：武将的hidden和shield
    def create_init_file(self):
        """创建包含武将定义的init.lua文件"""
        # 获取基础路径信息
        dir_path = os.path.dirname(os.path.abspath(self.filepath))
        base_name = os.path.splitext(os.path.basename(self.filepath))[0]
        extension_name = self.extension_name
        # 创建目标文件夹
        pkg_dir = os.path.join(dir_path, "pkg", base_name)
        os.makedirs(pkg_dir, exist_ok=True)
        
        # 创建init.lua文件
        init_file_path = os.path.join(pkg_dir, "init.lua")
        
        # 构建init文件内容
        content = f"""local extension = Package:new("{base_name}")
extension.extensionName = "{extension_name}"

extension:loadSkillSkelsByPath("./packages/{extension_name}/pkg/{base_name}/skills")

local trans = require("./packages/{extension_name}/pkg/{base_name}/trans")

"""
        
        # 添加武将定义
        for general in self.generals:
            name = general['name']
            localname = general['localname']
            kingdom = general['kingdom']
            hp = general['hp']
            maxhp = general['maxhp']
            gender = general['gender']
            skills = general['skills']
            related_skills = general['related_skills']


            
            # 创建武将代码
            if hp == maxhp and gender == "General.Male":
                general_code = f'General:new(extension, "{name}", "{kingdom}", {hp})'
            elif hp == maxhp:
                general_code = f'General:new(extension, "{name}", "{kingdom}", {hp}, {maxhp}, {gender})'
            else:
                general_code = f'General:new(extension, "{name}", "{kingdom}", {hp}, {maxhp})'
            
            # 分行添加武将和技能
    
            content += f'local {localname} = {general_code}\n'
            
            # 添加技能
            if skills:
                skill_list = ", ".join(['"' + s + '"' for s in skills])
                content += f'{localname}:addSkills {{ {skill_list} }}\n'
            
            # 添加相关技能
            if related_skills:
                related_list = ", ".join(['"' + s + '"' for s in related_skills])
                content += f'{localname}:addRelatedSkills {{ {related_list} }}\n'
            
            content += '\n'


            map=["hidden","shield","total_hidden"]
            for key in map:
                if key in general:
                    content += f'{localname}.{key} = {general[key]}\n'
        
        # 添加返回语句
        content += "\nreturn extension\n"
        
        # 写入文件
        try:
            with open(init_file_path, 'w', encoding='utf-8') as f:
                f.write(content)
            print(f"[*] 已创建初始化文件: {init_file_path}")
        except Exception as e:
            print(f"创建初始化文件失败: {init_file_path} | 错误: {str(e)}")

    def create_package_file(self):
        """创建包含拓展包基础的的init.lua文件"""
        # 获取基础路径信息
        dir_path = os.path.dirname(os.path.abspath(self.filepath))
        #base_name = os.path.splitext(os.path.basename(self.filepath))[0]
        extension_name = self.extension_name
        # 创建目标文件夹
        
        # 创建init.lua文件
        init_file_path = os.path.join(dir_path, "init.lua")
        
        # 构建init文件内容
        content = f"""
       local prefix = "packages.{extension_name}.pkg."

local modules = {{}}
local directories = FileIO.ls("packages/{extension_name}/pkg")
for _, dir in ipairs( directories) do
    local extension=require(prefix..dir)
    table.insert(modules, extension)
end

return modules

"""
        try:
            with open(init_file_path, 'w', encoding='utf-8') as f:
                f.write(content)
            print(f"[*] 已创建初始化文件: {init_file_path}")
        except Exception as e:
            print(f"创建初始化文件失败: {init_file_path} | 错误: {str(e)}")
        
    
    def mkSkillDir(self):
        """创建技能文件目录结构并写入技能内容"""
        if self.istrans:
            # 首先创建翻译文件
            self.create_translation_file()
            
            # 创建init.lua文件
            self.create_init_file()

            
            return 0
        # 获取基础路径信息
        dir_path = os.path.dirname(os.path.abspath(self.filepath))
        base_name = os.path.splitext(os.path.basename(self.filepath))[0]
        
        # 创建目标文件夹
        target_dir = os.path.join(dir_path, "pkg", base_name, "skills")
        os.makedirs(target_dir, exist_ok=True)

        
        i = 0
        n = len(self.skills.keys())

        # 写入技能文件
        for skill_name in self.skills:
            i += 1
            print("[*] 正在处理第 %d/%d 个技能：%s" % (i, n, skill_name))
            skill = self.skills[skill_name]
            
            # 清理非法文件名字符
            safe_name = re.sub(r'[\\/*?:"<>|]', '_', skill_name)
            file_path = os.path.join(target_dir, f"{safe_name}.lua")
            content = '\n\n'.join(skill.contents)
            content = self.clean_skill_content(content)
            recoder = SkillRecoder(skill_name, skill.name, content)
            result = '\n\n'.join(recoder.skillcode)
            
            try:
                with open(file_path, 'w', encoding='utf-8') as f:
                    f.write(result)

            except Exception as e:
                print(f"写入技能文件失败: {file_path} | 错误: {str(e)}")

    def _refactor_skill(self, skillObj: Skill) -> str:
        content = '\n\n'.join(skillObj.contents)

        # 不再添加翻译表到每个技能文件
        gpt = self.gpt
        n = 2  # 更新步骤数为2
        #result = SkillRecoder(skillObj.name, skillObj.name, content)
        return content

        try:
            print ("  [1/%d] 将技能主体结构调整为新版" % n)
            content = gpt.chat(gpt.basic_prompt, content)
            print ("  [2/%d] 调整self.name，cost_data等" % n)
            content = gpt.chat(gpt.misc_prompt, content)
            '''暂时不需要了
            print ("  [3/%d] 重构askFor系列函数" % n)
            content = gpt.chat(gpt.askto_prompt, content)
            '''
            content = content.replace('    ', '  ')
            
            return content
        except Exception as e:
            print(f"处理技能时发生错误: {str(e)}")
            # 出错时返回原始内容
            return '\n\n'.join(skillObj.contents)

    def clean_skill_content(self, content):
        # 去除注释
        # 先处理多行注释
        cleaned_content = re.sub(r'--\[\[(.*?)\]\]', '', content, flags=re.DOTALL)
        # 再处理单行注释，但保留注释前的代码
        #cleaned_content = re.sub(r'(^|[^-])--.*', r'\1', cleaned_content, flags=re.MULTILINE)
        return cleaned_content

    def extract_package_name(self,path):
        """从路径中提取包名（packages后面的部分）
        
        Args:
            path (str): 完整路径，例如 "C:/Users/tang/Desktop/study/game/test/FreeKill-release/packages/jbs"
            
        Returns:
            str: 包名，例如 "jbs"
        """
        # 使用正则表达式匹配packages/后面的部分
        match = re.search(r'packages[/\\]([^/\\]+)', path)
        if match:
            self.extension_name = match.group(1)
            return match.group(1)
        return None